<template>
    
        <div class="gateRpt2Wrapper">

            <div class="chartTitleLayout">
                <SectionTitle :text="title"  />
                <SchoolAreaSelect @select="handleSelect" :value="school" />
            </div>

            <ButtonGroup :buttons="btns"  style="margin-top: 20px;margin-bottom: 10px;" @select="handleSelectDate"/>

            <div :id="id" class="gateRpt2"></div>

            <!-- <div style="color:gray;text-align: center;font-size: 12px;">数据更新日期为：2025年3月6日12:00:00</div> -->
        </div>

        <van-popup v-model:show="showDetail" closeable position="bottom" :style="{ height: '70%' }" teleport="body" round destroy-on-close>
            <PersonVisitLogPopup :date="dateDetail" :school="school" :dateDuration="dateDuration" :gate="gate"/>            
        </van-popup>
    
    
</template>
<script lang="ts" setup>
import {type ECOption,initChart} from '@/util/echartsTool'
import { onMounted, onUnmounted } from 'vue';
import { type EChartsType } from 'echarts/core';
import SectionTitle from '@/components/SectionTitle.vue';
import SchoolAreaSelect from '@/components/form/schoolAreaSelect.vue';
import ButtonGroup from '@/components/buttonGroup.vue';
import { ref } from 'vue';
import type { GridReportProps } from '@/types/common';
import { formateDateYMD } from '@/util/dateTool';
import http from '@/api/request'
import PersonVisitLogPopup from '@/views/dashboard/rptPopup/personVisitLogPopup.vue';
import { saveLog } from '@/api/queryLog';

interface PersonRptData2Item{
    cnt:number,
    gate_name:string,
    school_area:string
}

interface PersonRptData2{
    rpt:PersonRptData2Item[]
}

const school = ref('')
const begin = ref();
const end = ref();
const showDetail = ref(false)
const dateDetail = ref('')
const dateDuration = ref();
const btns = ref(['近1周','近2周','近1月'])
const gate = ref('')



const handleSelect = (selectSchool:string)=>{
    school.value = selectSchool;
    saveLog("行人入校查询（校区）","rpt_click_person2",selectSchool);
    getData1();
}

const handleSelectDate = (index:number)=>{
    end.value = formateDateYMD(new Date());
    var d = new Date();
    if(index == 0) d.setDate(d.getDate()-7)
    if(index == 1) d.setDate(d.getDate()-14)
    if(index == 2) d.setDate(d.getDate()-30)
    begin.value = formateDateYMD(d);

    dateDuration.value = index;

    saveLog("行人入校查询（日期）","rpt_click_person2",btns.value[index]);
    
    getData1();
}


const {title='按校门统计',id} =  defineProps<GridReportProps>();

 
const option: ECOption = {
    
    tooltip: {},
   grid:{
    left:0
   },
    series: [
        {
            type: 'pie',
            radius: [10, 50],            
            
            left: 'left',
            width:'100%',
            itemStyle: {
                borderColor: '#fff',
                borderWidth: 1
            },
            data:[],
            label: {
                alignTo: 'edge',
                formatter: '{name|{b}}\n{c}人',
                minMargin: 1,
                edgeDistance: 2,
                fontSize:13,
                lineHeight: 20,
                rich: {
                    time: {
                        fontSize: 12,
                        color: '#999'
                    }
                }
            },
            labelLine: {
                length: 5,
                length2: 0,
                maxSurfaceAngle: 80
            },
            labelLayout: function (params:any) {

                const labelRect =  params.labelRect;
                const rect = params.rect;               

                

                const isLeft = params.labelRect.x < myChart.getWidth() / 2;
                const points = params.labelLinePoints;
                // Update the end point.
                points[2][0] = isLeft? params.labelRect.x  : params.labelRect.x + params.labelRect.width;
                return {
                    labelLinePoints: points,
                    labelRect:labelRect,
                    rect:rect
                };
            },     
            tooltip: {
                trigger: 'item',
                triggerOn:'click',
                enterable:true,                
                formatter: function (params:any) {
                    console.log()
                    // 返回一个包含 HTML 按钮的字符串
                    return `
                        <div  class='chartsShowDetailBtn2Wrapper' data-school='${params.data.schoolArea}' data-gate='${params.data.gateName}'>
                            <div data-school='${params.data.schoolArea}' data-gate='${params.data.gateName}'>${params.name}</div>
                            <div data-school='${params.data.schoolArea}' data-gate='${params.data.gateName}'>行人入校人数: ${params.value}人 </div>
                            <div class='chartsShowDetailBtn2' style='color:blue' data-school='${params.data.schoolArea}' data-gate='${params.data.gateName}'>查看详情</div>
                        </div>
                    `;
                },
                
            } 
    
        }
    ]
    };
var myChart :EChartsType;

onMounted(()=>{
    end.value = formateDateYMD(new Date());
    var d = new Date();
    d.setDate(d.getDate()-7)
    begin.value = formateDateYMD(d);


    init();
    getData1();
})


const getData1 = ()=>{
    http.get<PersonRptData2>('/person/rpt2',{
        begin:begin.value,
        end:end.value,
        school:school.value
    }).then((resp)=>{
        
      var temp:any[] = [];

        resp.data?.rpt.forEach((item)=>{            
            var schoolArea = ''
            var gateName = item.gate_name;
            if(item.school_area){
                schoolArea = item.school_area+'';
            }else{
                if(item.gate_name == '西门'){
                    item.gate_name = '小西门'
                }
            }


           temp.push({
            name:schoolArea+item.gate_name,
            value:item.cnt,
            schoolArea,
            gateName
           })
        })

        
        //@ts-ignore
        option.series[0].data = temp;

        myChart.setOption(option);
    })
}


onUnmounted(()=>{
    myChart.dispose();
})



const init = ()=>{
    // 基于准备好的dom，初始化echarts实例
    myChart = initChart(document.getElementById(id));
    
    // 绘制图表
    myChart.setOption(option);

    myChart.on('showTip',()=>{
        const tooltips = document.querySelector('.chartsShowDetailBtn2Wrapper');
        if(tooltips){
            tooltips.addEventListener('click',(e)=>{
                const tagrget = e.target as HTMLElement;
                const schoolName = tagrget.getAttribute('data-school'); //门口   
                const gateName = tagrget.getAttribute('data-gate'); //门口   
                showDetail.value = true;
                gate.value = gateName+"";
                school.value = schoolName+"";
                saveLog("点击行人入校报表",'rpt_click_item_person2',schoolName+""+gateName+"");
            })
        }
    })
}
</script>
<style lang="less" scoped>
  .gateRpt2Wrapper{
        background-color: #fff;
        padding:10px;
        margin:10px;
        border-radius: 6px;
        .gateRpt2{
            width: 100%;
            height: 300px;
        }
    }

    .chartTitleLayout{
        display: flex;
        justify-content: space-between;
    }
</style>